package org.javaboy.shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.javaboy.shiro.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class LoginController {

    @PostMapping("/doLogin")
    public String doLogin(User user) {
        //subject 就是 Shiro 中的用户，没登录就是匿名用户
        Subject subject = SecurityUtils.getSubject();
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
            //开启 RememberMe 登录
            token.setRememberMe(true);
            //执行登录，传入 AuthenticationToken，不同类型的 AuthenticationToken 代表了不同的登录方式
            subject.login(token);
            //注销登录
//            subject.logout();
            //如果没有抛异常出来，就说明登录成功了
            return "redirect:/index.html";
        } catch (UnknownAccountException e) {
            System.out.println("账户不存在");
            return "redirect:/login.html";
            //            throw new RuntimeException(e);
        } catch (IncorrectCredentialsException e) {
            System.out.println("密码输入错误");
            return "redirect:/login.html";
        }
    }
}
